package com.xi.demo.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/chat")
public class ChatController {

//    private final ChatClient chatClient;
//
//    public ChatController(ChatClient.Builder chatClient) {
//        this.chatClient = chatClient.build();
//    }

    @Autowired
    private ChatClient chatClient;

    @RequestMapping("/message1")
    public String getAns1(String inputMes){
        return chatClient.prompt()
                .user(inputMes)
                .call()   // 一次性输出
                .content();
    }


    @RequestMapping(value = "/message2",produces = "text/html;charset=utf-8" )
    public Flux<String> getAns2(String inputMes){
        return chatClient.prompt()
                .advisors(new SimpleLoggerAdvisor())
                .user(inputMes)
                .stream()//流式输出
                .content();
    }


    static class Menu{
        public String name;

        public List<String> m;

        Menu(String name, List<String> m){
            this.name = name;
            this.m = m;
        }

        @Override
        public String toString() {
            return "Menu {" +
                    "name='" + name + '\'' +
                    ", items=" + m +
                    '}';
        }
    }


    @RequestMapping(value = "/message3",produces = "text/html;charset=utf-8" )
    public String getAns3(String inputMes){
        Menu entity = chatClient.prompt()
                .advisors(new SimpleLoggerAdvisor())
                .user("请帮我写出" + inputMes + "的菜单！")
                .call()
                .entity(Menu.class);

        return entity.toString();
    }

    @RequestMapping(value = "/SSE")
    public void sse(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        String s = "";
        PrintWriter writer = response.getWriter();
        for (int i = 0; i < 10; i++) {
            s = "data: " + new Date() + i + "\n\n";
            writer.append(s);
            writer.flush();
            Thread.sleep(1000l);
        }

        writer.append("event: end \n " + " data: \"\" \n\n");
        writer.flush();
    }


}
